import { UserModel } from "../model/userModel";
import { isEmpty } from "../utils";
import { KoaResult } from "../constants/interface";
import { USER_ALREADY_EXITS } from "../constants/errorType";
const db = require("../app/database");

class UserService {
    public async getUserInfoById(ctx: any, next: Function, params: any): Promise<any> {
        let json: KoaResult;
        const [res,] = await db.execute(`select * from tb_user where id = ${params.id}`);
        const user = UserModel.create(res[0]);
        if (isEmpty(user)) {
            json = new KoaResult(user, "用户不存在", 500);
        }
        json = new KoaResult(user, "", 0);
        return json;
    }
    /**
     * 
     * @param ctx 
     * @param next 
     * path: /api/user/login
     * params: {
     *              password:string,
     *              mobile: number     
     *         }
     * @returns 
     */
    public async login(ctx: any, next: Function): Promise<any> {
        const params:any = ctx.request.body;
        const [res,] = await UserModel.query(params.mobile);
        if (res.length >= 1) {
            return ctx.app.emit('error', new Error(USER_ALREADY_EXITS), ctx);
        }

        console.log(res);
        
        
    }

    /**
     * 
     * @param ctx 
     * @param next 
     * path: /api/user/register
     * params: {
     *              username:string,
     *              password:string,
     *              sex:string 0|1
     *              mobile: number     
     *              [email:string]
     *         }
     * @returns 
     */
    public async register(ctx: any, next: Function): Promise<any> {
        let json: KoaResult;
        let errorMsg: string;
        const params: any = ctx.request.body;
        if (!params.username) {
            errorMsg = "用户名不能为空"
        } else if (!params.password) {
            errorMsg = "用户密码不能为空"
        } else if (!params.mobile) {
            errorMsg = "用户手机号码不能为空"
        } else if (!params.sex) {
            errorMsg = "用户性别不能为空"
        } else if (params.sex != '0' && params.sex != '1') {
            errorMsg = "用户性别错误"
        }

        if (errorMsg) {
            json = new KoaResult(null, errorMsg, 40004);
            ctx.body = json
            return;
        }

        const [res,] = await UserModel.query(params.mobile);

        if (res.length >= 1) {
            return ctx.app.emit('error', new Error(USER_ALREADY_EXITS), ctx);
        }

        const [userRes,] = await UserModel.create(params);

        if (userRes.affectedRows >= 1) {
            json = new KoaResult(null, "用户注册成功", 0);
            ctx.body = json;
            return;
        }

        return ctx.app.emit('error', new Error(), ctx);
    }
}

module.exports = new UserService();